package com.lujieni.netty.c3;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.TimeUnit;

public class TestNettyFuture {

    public static void main(String[] args) {

        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();

        Future<Integer> future = nioEventLoopGroup.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            int i = 100/0;
            return 100;
        });

        // asynchronous non-blocking
        future.addListener(new GenericFutureListener<Future<Integer>>() {
            @Override
            public void operationComplete(Future<Integer> future) throws Exception {
                // if exception happened, getNow() will return null even if task is over
                System.out.println(Thread.currentThread().getName() + ":"+future.getNow());
                // Integer i = future.get(); if exception happened,get() will throw exception
                System.out.println(future.isSuccess());
                System.out.println(future.isDone());
                nioEventLoopGroup.shutdownGracefully();
            }
        });


    }
}
